package com.tbq.game.service.socket.netty

import io.netty.channel.ChannelDuplexHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent

class StateCheckChannelHandler: ChannelDuplexHandler() {

    override fun userEventTriggered(ctx: ChannelHandlerContext?, evt: Any?) {
        if (evt is IdleStateEvent) {
            when {
                evt.state() == IdleState.ALL_IDLE -> {
                    NettyLog.e("发送心跳：" + NettyClient.endFlag)
                    ctx?.channel()?.writeAndFlush(NettyClient.endFlag)   // 发送心跳消息
                }
                evt.state() == IdleState.READER_IDLE -> {
                    //                NettyLog.e("读取信息超时：READER_IDLE，准备重连");
                    NettyClient.isConnections = false
                    NettyClient.loopConnect(ctx?.channel(), Exception("读取信息超时：READER_IDLE，准备重连"))
                }
                evt.state() == IdleState.WRITER_IDLE -> {
                    //                NettyLog.e("写入信息超时：WRITER_IDLE，准备重连");
                    NettyClient.isConnections = false
                    NettyClient.loopConnect(ctx?.channel(), Exception("写入信息超时：WRITER_IDLE，准备重连"))
                }
            }
        }
        super.userEventTriggered(ctx, evt)
    }
}